#!/usr/bin/env bash
# yitong.bai@qq.com
# Library for install functions

function InstallDockerRegistryIfNotInstalled() {
  local listenHost="$1"
  local listenPort="$2"
  local dataPath="$3"

  # if docker ps | grep "registry:2";then
  #   docker rm -f registry &> /dev/null
  #   rm -rf "${registry_data}"
  # fi

  # if ! docker run \
  #   -d \
  #   -v "${registry_data}":/var/lib/registry \
  #   -p 5000:5000  \
  #   --name registry \
  #   registry:2 &> /dev/null;
  # then
  #   return 1
  # fi
  # docker container update --restart=always registry &> /dev/null

  # 将docker registry改为二进制部署

  [ -f "/usr/local/bin/registry" ] && return 0


}

# 安装ansible，需要先安装python3
function InstallAnsibleIfNotInstalled() {
  local requirements="${1}"
  
  if ! ansible &> /dev/null; then
    python3 -m pip install --user --upgrade pip &> /dev/null 
    python3 -m pip install --user --quiet -r "${requirements}" &> /dev/null

    export PATH=/root/.local/bin:$PATH

    grep "# Gaea Ansible PATH" ~/.bashrc && return 0
    echo "# Gaea Ansible PATH" >> ~/.bashrc
    echo "export PATH=/root/.local/bin:$PATH" >> ~/.bashrc
    #source "$HOME/.bashrc"
  fi
}

function StartupDockerService() {
  # local dataRoot="${1}"
  # local insecureRegistry="${2}"

#   cat > /etc/docker/daemon.json <<EOF
# {
# "data-root": "${dataRoot}",
# "insecure-registries": ["${insecureRegistry}"]
# }
# EOF

  [ "$#" -eq 0 ] || \
  (
    local insecureRegistry="${1}"
    [ -n "${insecureRegistry}" ] \
    && echo {"insecure-registries": ["${insecureRegistry}"]} > /etc/docker/daemon.json
  )

  if ! ( systemctl start docker || systemctl restart docker ); then
    return 1
  fi
}

function StartupDockerRegistryService() {
  [ -f "/usr/local/bin/registry" ] || return 1

  /usr/local/bin/registry
}

function StartupHttpService() {
  if ! (systemctl start nginx || systemctl restart nginx ); then
    return 1
  fi
}